package com.sbl.jdbctemplate;

import com.sbl.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
        //=====================    通过XML配置   ========================
        //1. 获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2. 获取对象
        JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3. 执行操作
        //3.1 查询返回一行一列（使用聚合函数，但不加group by 子句）
//        jt.execute("insert INTO account (name ,money)values ('凯杰',1000)");


        //3.3 保存数据 (插入添加、更新、删除数据和更新数据都叫保存)
        //3.3.1 插入数据
//      jt.update("insert into account(name ,money)values (?,?)","qwe",6666f);
        //3.3.2 更新数据
//      jt.update("update account set name=?,money=? where id=?","ccc",30000,7);


        //3.4.1 查询所有数据( 行数据映射为对象)。查询钱大雨6666的数据（ query(String sql, RowMapper<T> rowMapper, @Nullable Object... args)
        //                                                              其实是手动去写RowMapper转换映射implements RowMapper；这里为了方便直接用的框架的
        //                                                              不推荐这样，forObject这么用）
        List<Account> accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),6666);
        for (Account account:accounts){
            System.out.println(account);
        }
        //3.4.2.1 查询一个数据(jt.query 返回的是一个List列表；public <T> List<T> query)
//        List<Account> accounts2 = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),5);
//        System.out.println(accounts2.isEmpty()?"没有内容":accounts2.get(0));
        //3.4.2.2 查询一个数据，通过queryForObject
        Account account = jt.queryForObject("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),5);
        System.out.println(account);

        //查询返回一行一列，（ queryForObject(String sql, Class<T> requiredType, @Nullable Object... args) ）；只能传入基本包装类
        Long count = jt.queryForObject("select COUNT(*) from account where money > ?",Long.class,1000f);
        System.out.println(count);
    }
}
